﻿using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using Model;
using Newtonsoft.Json;

namespace Business
{
    public class ElemeRepository
    {
        string eleme_api_key = ConfigurationManager.AppSettings["eleme_api_key"];
        string eleme_api_secret = ConfigurationManager.AppSettings["eleme_api_secret"];
        string eleme_api_url = ConfigurationManager.AppSettings["eleme_api_url"];
        //string eleme_restaurant_id = ConfigurationManager.AppSettings["eleme_restaurant_id"];

        /// <summary>
        /// 获取字符串的HEX Code
        /// </summary>
        /// <param name="s"></param>
        /// <returns></returns>
        public static string HexString(string s)
        {
            string hex = "";
            foreach (char c in s)
            {
                int tmp = c;
                hex += String.Format("{0:x2}", (uint)System.Convert.ToUInt32(tmp.ToString()));
            }
            return hex;
        }

        /// <summary>
        /// 对字符串进行SHA1加密
        /// </summary>
        /// <param name="strIN">需要加密的字符串</param>
        /// <returns>密文</returns>
        public static string Sha1Encrypt(string s)
        {
            byte[] strRes = Encoding.UTF8.GetBytes(s);
            HashAlgorithm iSha = new SHA1CryptoServiceProvider();
            strRes = iSha.ComputeHash(strRes);
            StringBuilder enText = new StringBuilder();
            foreach (byte iByte in strRes)
            {
                enText.AppendFormat("{0:x2}", iByte);
            }
            return enText.ToString();
        }
        /// <summary>
        /// 获取餐厅
        /// </summary>
        /// <param name="requestMessage"></param>
        /// <param name="returnMessage"></param>
        /// <returns></returns>
        public bool GetRestaurant(out string requestMessage, out JObject returnMessage)
        {
            try
            {
                DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));
                var timestamp = (long)Math.Round((DateTime.Now - startTime).TotalMilliseconds);
                var baseUrl = eleme_api_url + "restaurant/own";
                var url_test_a = baseUrl + "/?consumer_key=" + eleme_api_key + "&timestamp=" + timestamp + eleme_api_secret;
                var url_test_b_hex = HexString(url_test_a);
                var sig = Sha1Encrypt(url_test_b_hex);
                var requestUrl = baseUrl + "/?consumer_key=" + eleme_api_key + "&sig=" + sig + "&timestamp=" + timestamp;
                var httpClient = new HttpClient();
                HttpResponseMessage response = httpClient.GetAsync(requestUrl).Result;
                JObject result = JObject.Parse(response.Content.ReadAsStringAsync().Result);
                requestMessage = url_test_a;
                returnMessage = result;
                if (result.Value<int>("code") == 200)
                    return true;
                return false;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        /// 获取餐厅当天订单(已处理或已取消)
        /// </summary>
        /// <param name="day"></param>
        /// <param name="restaurant_id"></param>
        /// <param name="returnMessage"></param>
        /// <returns></returns>
        public bool GetOrderByDay(string day, int restaurant_id, out JObject returnMessage)
        {
            try
            {
                var statuses = "-1%2C2";
                DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));
                var timestamp = (long)Math.Round((DateTime.Now - startTime).TotalMilliseconds);
                var baseUrl = eleme_api_url + "orders/batch_get";
                var url_test_a = baseUrl + "/?consumer_key=" + eleme_api_key + "&day=" + day + "&restaurant_id=" + restaurant_id + "&statuses=" + statuses + "&timestamp=" + timestamp + eleme_api_secret;
                var url_test_b_hex = HexString(url_test_a);
                var sig = Sha1Encrypt(url_test_b_hex);
                var requestUrl = baseUrl + "/?consumer_key=" + eleme_api_key + "&day=" + day + "&restaurant_id=" + restaurant_id + "&sig=" + sig + "&statuses=" + statuses + "&timestamp=" + timestamp;
                var httpClient = new HttpClient();
                HttpResponseMessage response = httpClient.GetAsync(requestUrl).Result;
                JObject result = JObject.Parse(response.Content.ReadAsStringAsync().Result);
                returnMessage = result;
                if (result.Value<int>("code") == 200)
                    return true;
                return false;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        public bool GetOrderInfo(long eleme_order_id, int tp_id, out JObject returnMessage)
        {
            try
            {
                DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));
                var timestamp = (long)Math.Round((DateTime.Now - startTime).TotalMilliseconds);
                var baseUrl = eleme_api_url + "order/" + eleme_order_id;
                var url_test_a = baseUrl + "/?consumer_key=" + eleme_api_key + "&timestamp=" + timestamp + "&tp_id=" + tp_id + eleme_api_secret;
                var url_test_b_hex = HexString(url_test_a);
                var sig = Sha1Encrypt(url_test_b_hex);
                var requestUrl = baseUrl + "/?consumer_key=" + eleme_api_key + "&sig=" + sig + "&timestamp=" + timestamp + "&tp_id=" + tp_id;
                var httpClient = new HttpClient();
                HttpResponseMessage response = httpClient.GetAsync(requestUrl).Result;
                JObject result = JObject.Parse(response.Content.ReadAsStringAsync().Result);
                returnMessage = result;
                if (result.Value<int>("code") == 200)
                    return true;
                return false;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        /// 批量上传库存
        /// </summary>
        /// <param name="restaurant_id">餐厅id</param>
        /// <param name="lstDCInventory">库存信息</param>
        /// <param name="returnMessage">返回结果</param>
        /// <returns></returns>
        public bool UpdateStockByTp_FoodId(string restaurant_id, List<DCInventory> lstDCInventory, out JObject returnMessage)
        {
            try
            {
                //lstDCInventory.Add(new DCInventory { GOODSCODE = "123", USEFULQTY = 12 });
                //lstDCInventory.Add(new DCInventory { GOODSCODE = "456", USEFULQTY = 45 });
                //lstDCInventory.Add(new DCInventory { GOODSCODE = "789", USEFULQTY = 78 });
                JObject JObject_stock_info = new JObject();
                JObject JObject_restaurant = new JObject();
                foreach (var item in lstDCInventory)
                {
                    JObject_restaurant.Add(item.GOODSCODE, item.USEFULQTY);
                }
                JObject_stock_info.Add(restaurant_id.ToString(), JObject_restaurant);
                string stock_info = JsonConvert.SerializeObject(JObject_stock_info);
                string stock_info_url = System.Web.HttpUtility.UrlEncode(stock_info, Encoding.UTF8).ToUpper();
                DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));
                var timestamp = (long)Math.Round((DateTime.Now - startTime).TotalMilliseconds);
                var baseUrl = eleme_api_url + "foods/stock";
                var url_test_a = baseUrl + "/?consumer_key=" + eleme_api_key + "&stock_info=" + stock_info_url + "&timestamp=" + timestamp + eleme_api_secret;
                var url_test_b_hex = HexString(url_test_a);
                var sig = Sha1Encrypt(url_test_b_hex);

                var param = new Dictionary<string, string> {
                   {"stock_info", stock_info}
                };
                var requestUrl = baseUrl + "/?consumer_key=" + eleme_api_key + "&sig=" + sig + "&timestamp=" + timestamp;
                var httpClient = new HttpClient();
                HttpResponseMessage response = httpClient.PutAsync(requestUrl, new FormUrlEncodedContent(param)).Result;
                JObject result = JObject.Parse(response.Content.ReadAsStringAsync().Result);
                returnMessage = result;
                if (result.Value<int>("code") == 200)
                    return true;
                return false;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 根据饿了么商品food_id修改商品库存
        /// </summary>
        /// <returns></returns>
        public int UpdateStockByFoodId(JObject job, out string requestMessage, out JObject returnMessage)
        {
            try
            {
                int stock = job.Value<int>("stock");
                DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));
                var timestamp = (long)Math.Round((DateTime.Now - startTime).TotalMilliseconds);
                var baseUrl = eleme_api_url + "food/" + job.Value<int>("food_id");
                var url_test_a = baseUrl + "/?consumer_key=" + eleme_api_key + "&max_stock=" + stock + "&stock=" + stock + "&timestamp=" + timestamp + eleme_api_secret;
                var url_test_b_hex = HexString(url_test_a);
                var sig = Sha1Encrypt(url_test_b_hex);
                var param = new Dictionary<string, string> {
                   {"max_stock", job.Value<string>("stock") },
                   {"stock", job.Value<string>("stock")}
                };
                var requestUrl = baseUrl + "/?consumer_key=" + eleme_api_key + "&sig=" + sig + "&timestamp=" + timestamp;
                var httpClient = new HttpClient();
                HttpResponseMessage response = httpClient.PutAsync(requestUrl, new FormUrlEncodedContent(param)).Result;
                JObject result = JObject.Parse(response.Content.ReadAsStringAsync().Result);
                requestMessage = url_test_a;
                returnMessage = result;
                if (result.Value<int>("code") == 200)
                    return 1;
                return 0;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 根据饿了么商品food_id修改商品价格
        /// </summary>
        /// <returns></returns>
        public int UpdatePriceByFoodId(JObject job, out string requestMessage, out JObject returnMessage)
        {
            try
            {
                decimal price = job.Value<decimal>("price");
                DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));
                var timestamp = (long)Math.Round((DateTime.Now - startTime).TotalMilliseconds);
                var baseUrl = eleme_api_url + "food/" + job.Value<int>("food_id");
                var url_test_a = baseUrl + "/?consumer_key=" + eleme_api_key + "&price=" + price + "&timestamp=" + timestamp + eleme_api_secret;
                var url_test_b_hex = HexString(url_test_a);
                var sig = Sha1Encrypt(url_test_b_hex);
                var param = new Dictionary<string, string> {
                   {"price", job.Value<string>("price") }
                };
                var requestUrl = baseUrl + "/?consumer_key=" + eleme_api_key + "&sig=" + sig + "&timestamp=" + timestamp;
                var httpClient = new HttpClient();
                HttpResponseMessage response = httpClient.PutAsync(requestUrl, new FormUrlEncodedContent(param)).Result;
                JObject result = JObject.Parse(response.Content.ReadAsStringAsync().Result);
                requestMessage = url_test_a;
                returnMessage = result;
                if (result.Value<int>("code") == 200)
                    return 1;
                return 0;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }


        public void ImportElemeGoodsInfo()
        {
            try
            {
                DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));
                var timestamp = (long)Math.Round((DateTime.Now - startTime).TotalMilliseconds);
                var baseUrl = eleme_api_url + "restaurant/836218/menu";
                var url_test_a = baseUrl + "/?consumer_key=" + eleme_api_key + "&timestamp=" + timestamp + eleme_api_secret;
                var url_test_b_hex = HexString(url_test_a);
                var sig = Sha1Encrypt(url_test_b_hex);
                var requestUrl = baseUrl + "/?consumer_key=" + eleme_api_key + "&sig=" + sig + "&timestamp=" + timestamp;
                var httpClient = new HttpClient();
                HttpResponseMessage response = httpClient.GetAsync(requestUrl).Result;
                JObject result = JObject.Parse(response.Content.ReadAsStringAsync().Result);
                if (result.Value<int>("code") == 200)
                {
                    JArray jarray = result.Value<JObject>("data").Value<JArray>("restaurant_menu");
                    foreach (var item in jarray)
                    {
                        //foreach (var food in item.Value<JArray>("foods"))
                        //    base.Invoke(CCI.Name.create_elemegoodsinfo, food);
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public JArray ElemeGoodsInfoList()
        {
            try
            {
                JArray jarray = new JArray();
                DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));
                var timestamp = (long)Math.Round((DateTime.Now - startTime).TotalMilliseconds);
                var baseUrl = eleme_api_url + "restaurant/836218/menu";
                var url_test_a = baseUrl + "/?consumer_key=" + eleme_api_key + "&timestamp=" + timestamp + eleme_api_secret;
                var url_test_b_hex = HexString(url_test_a);
                var sig = Sha1Encrypt(url_test_b_hex);
                var requestUrl = baseUrl + "/?consumer_key=" + eleme_api_key + "&sig=" + sig + "&timestamp=" + timestamp;
                var httpClient = new HttpClient();
                HttpResponseMessage response = httpClient.GetAsync(requestUrl).Result;
                JObject result = JObject.Parse(response.Content.ReadAsStringAsync().Result);
                if (result.Value<int>("code") == 200)
                    jarray = result.Value<JObject>("data").Value<JArray>("restaurant_menu");

                return jarray;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
    }
}
